//
//  SLAddNewFriendViewModel.m
//  StarLight
//
//  Created by Duke.wu on 16/6/2.
//  Copyright © 2016年 Duke.Wu. All rights reserved.
//

#import "SLAddNewFriendViewModel.h"
#import <AddressBook/AddressBook.h>
#import "NSString+someMethods.h"
#import "SLNetWork.h"




@implementation SLAddNewFriendViewModel


//- (instancetype)init{
//  if (self = [super init]) {
//    [self getOperbuddylist];
//  }
//  return self;
//}


- (void)synAddresser{
  [self acceptAddress];
}


/**
 *  获取好友操作列表
 */
- (void)getOperbuddylist{
  @weakify(self)
  NSString *getUrl = [NSString stringWithFormat:@"%@/user/operbuddylist?uid=%@",baseUrl,[DEFAULTS objectForKey:@"loginInformation"][@"id"]];
  [SLNetWork getDataWithRequest:getUrl complete:^(id respond, NSError *error) {
    @strongify(self);
    [self.operbuddyList removeAllObjects];
    
    self.operbuddyList = [SLOperbuddyModel mj_objectArrayWithKeyValuesArray:respond[@"data"]];
  }];
}


- (void)upToServiceWithContact:(NSString *)contacts{
  
  if(contacts.length > 0){
    NSDictionary *para = @{@"uid":[DEFAULTS objectForKey:@"loginInformation"][@"id"],@"contacts":contacts};
    NSString *postUrl = [NSString backUrlWithService:@"user" methodName:@"synchr"];
    
    @weakify(self)
    [SLNetWork postDataWithParameters:para postUrl:postUrl complete:^(id respond, NSError *error) {
      
      if (!error) {
        @strongify(self)
        self.operbuddyList = [SLOperbuddyModel mj_objectArrayWithKeyValuesArray:respond[@"sucess"]];
      }      
    }];

  }else{
    [SVProgressHUD showImage:nil status:@"暂无联系人"];
  }

}

- (void)upToServiceUserWithContact:(NSString *)contacts{
    
    if(contacts.length > 0){
        NSDictionary *para = @{@"uid":[DEFAULTS objectForKey:@"loginInformation"][@"id"],@"contacts":contacts};
        NSString *postUrl = [NSString backUrlWithService:@"user" methodName:@"synchrfollow"];
        
        @weakify(self)
        [SLNetWork postDataWithParameters:para postUrl:postUrl complete:^(id respond, NSError *error) {
            
            if (!error) {
                @strongify(self)
                self.operbuddyList = [SLOperbuddyModel mj_objectArrayWithKeyValuesArray:respond[@"sucess"]];
            }
        }];
        
    }else{
        [SVProgressHUD showImage:nil status:@"暂无联系人"];
    }
    
}




- (void)acceptAddress{
  
  ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
  
  if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
    ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error){
      
      CFErrorRef *error1 = NULL;
      ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error1);
          [self copyAddressBook:addressBook];
    });
  }
  else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized){
    
    CFErrorRef *error = NULL;
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
        [self copyAddressBook:addressBook];
  }
  else {
    dispatch_async(dispatch_get_main_queue(), ^{
      // 更新界面
      [SVProgressHUD showErrorWithStatus:@"没有获取通讯录权限"];
    });
  }

}

- (void)copyAddressBook:(ABAddressBookRef)addressBook{
  CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBook);
  CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
  
  NSMutableString *contacts;
  for ( int i = 0; i < numberOfPeople; i++){
    ABRecordRef person = CFArrayGetValueAtIndex(people, i);
  
    NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
    NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
    
    //读取电话多值
    ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
    NSString *newPhone;
    for (int k = 0; k<ABMultiValueGetCount(phone); k++)
    {
      //获取該Label下的电话值
      NSString * personPhone = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phone, k);
      
      if (personPhone != nil) {
        newPhone = [NSString stringDeleteString:personPhone];
      }
    }
    
    NSString *name;
    
    if(firstName == nil || lastName == nil){
      if (firstName == nil) {
        name = lastName;
      }else if(lastName == nil){
        name = firstName;
      }
    }else{
      name = [NSString stringWithFormat:@"%@%@",lastName,firstName];
    }
    
    
    if (newPhone != nil && name != nil) {
        NSString *person = [NSString stringWithFormat:@"%@,%@",name,newPhone];
      if (contacts != nil) {
        [contacts appendFormat:@"@%@", person];
      }else{
        contacts = [NSMutableString stringWithFormat:@"%@",person];
      }
    }
  }
  [self upToServiceUserWithContact:contacts];
}





@end


@implementation SLOperbuddyModel

+ (NSDictionary *)mj_replacedKeyFromPropertyName{
  return @{@"userId":@"id"};
}

@end










